<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 支付模型
 * @author www.dingwei.cn
 */

class ConsumerPayModel extends MY_Model{
	
	public $tbPayOrder = 'consumer_pay_order';
	
	/**
	 * 保存预支付订单
	 * @param array $data 数据
	 * @param number $code
	 * @author zyl
	 */
	public function savePayOrder($data,$code = 0){
		if ($code){
			$this->db->where('code',$code);
			$query = $this->update($this->tbPayOrder, $data);
			return $query === false ? false : true;
		}else{
			return $this->insert($this->tbPayOrder, $data);
		}
	}
	
	/**
	 * 获取信息
	 * @param integer $consumerId 消费者id
	 * @param string  $code 
	 * @author zyl
	 */
	public function getInfo($consumerId = 0,$code = 0){
		if (!$consumerId && ! $code){
			return array();
		}
		
		if ($consumerId){
			$this->db->where('consumer_id',$consumerId);
		}
		if ($code){
			$this->db->where('code',$code);
		}
		return $this->getOne($this->tbPayOrder);
	}
	
	/**
	 * 支付宝支付下单
	 */
	public function _getAliPay($code,$amount = 0.01){
		//$amount = 0.01;
		include APPPATH.'libraries/AliPay/AopSdk.php';
		
		$aop = new AopClient;
		$aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
		$aop->appId = getCustomConfig('alipay_appid',get_instance()->port);
		$aop->rsaPrivateKey = getCustomConfig('alipayrsaPrivateKey',get_instance()->port);
		$aop->alipayrsaPublicKey = getCustomConfig('alipayrsaPublicKey',get_instance()->port);
		$aop->format = "json";
		$aop->charset = "UTF-8";
		$aop->signType = "RSA2";
		//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		$request = new AlipayTradeAppPayRequest();
		//SDK已经封装掉了公共参数，这里只需要传入业务参数
		$bizcontent = json_encode(array(
				'body'=>'戈壁市集支付宝',
				'subject'=>'戈壁市集',
				'out_trade_no'=>$code,
				'timeout_express'=>'30m',
				'total_amount'=>$amount,
				'product_code'=>'QUICK_MSECURITY_PAY',
		));
		
		$request->setNotifyUrl(getUrl('app/pay/zfbCallback'));
		$request->setBizContent($bizcontent);
		//这里和普通的接口调用不同，使用的是sdkExecute
		$response = $aop->sdkExecute($request);
		//htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
		return $response;//就是orderString 可以直接给客户端请求，无需再做处理。
	}
	
	/**
	 * 处理支付宝回调
	 * @return boolean
	 */
	public function _aliCallback(){
		
		include APPPATH.'libraries/AliPay/AopSdk.php';
		$aop = new AopClient;
		$aop->alipayrsaPublicKey = getCustomConfig('alipayPublicKey',get_instance()->port);//支付宝公钥
		
		//		$str = '{"gmt_create":"2017-11-30 14:03:33","charset":"UTF-8","seller_email":"plalading@163.com","subject":"\u8bda\u4fe1\u5546\u76df","sign":"B1Vyipn24kHJwXyLSgeDymTHrL0XXd6Sm3OtlrSoK60ivCfR9TAl\/+cgJDNX7ye7\/S7ka39lgYBDL23doeId\/8MnmKQGoaQNE1H56EifTkdlvqkOeN33JxxoTVhVRf5xRJCzdnGgGicKtx\/EmHXOhhNGR2oJ9OQbzUICKhZRrAw9IlH98Xj+qU2SvpBHgFLLJRlOEfhhKro11cPZCiwC1bESdSSMMmkM038SIZ4P5m\/Pkv2MIQ7nk2VSTK3Tdk6u8wVONHKE2XyL2yZDG+vz3wDNJtwoOgOT7\/4pwFK1tQc3I\/ypd4nzEJWlL9LzC\/nNIY6su7YkJ8iPT0EizgPPWQ==","body":"\u5546\u76df\u652f\u4ed8\u5b9d","buyer_id":"2088502730316261","invoice_amount":"0.01","notify_id":"cb932933a7e86a602529c406bcbb82ci0d","fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"ALIPAYACCOUNT\"}]","notify_type":"trade_status_sync","trade_status":"TRADE_SUCCESS","receipt_amount":"0.01","app_id":"2017110209678597","buyer_pay_amount":"0.01","sign_type":"RSA2","seller_id":"2088821469413675","gmt_payment":"2017-11-30 14:03:33","notify_time":"2017-11-30 14:07:18","version":"1.0","out_trade_no":"20171130020325201300","total_amount":"0.01","trade_no":"2017113021001004260538452666","auth_app_id":"2017110209678597","buyer_logon_id":"991***@qq.com","point_amount":"0.00"}';
		//		$str = json_decode($str,true);
		
		$flag = $aop->rsaCheckV1($_POST, NULL , 'RSA2');
		$trade_status = post('trade_status');//获取当前交易状态
		if($flag && ($trade_status == 'TRADE_SUCCESS' || $trade_status == 'TRADE_FINISHED')){
			return TRUE;
		}
		return FALSE;
	}

    /**
     * 支付宝退款
     * @param $code  预支付订单号
     * @param $refundAmount  退款金额
     * @param $refundCode  退款单号即售后单号
     *@return  $resultCode==10000   成功
     */
    public function zfbRefund($code, $refundAmount, $refundCode){
        include APPPATH.'libraries/AliPay/AopSdk.php';

        $appId = getCustomConfig('alipay_appid','consumer');
        $rsaPrivateKey = getCustomConfig('alipayrsaPrivateKey','consumer');
        $alipayrsaPublicKey = getCustomConfig('alipayrsaPublicKey','consumer');

        $aop = new AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $appId;
        $aop->rsaPrivateKey = $rsaPrivateKey;
        $aop->alipayrsaPublicKey = $alipayrsaPublicKey;
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new AlipayTradeRefundRequest ();
        $bizcontent=array(
            'out_trade_no' => $code,
            'trade_no' => '',
            'refund_amount' => $refundAmount,
            'refund_reason' => '正常退款',
            'out_request_no' => $refundCode,
            'operator_id' => '1',
            'store_id' => '1',
            'terminal_id' => '1',
        );
        $bizcontent=json_encode($bizcontent);
        $request->setBizContent($bizcontent);

        $result = $aop->execute ( $request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;

        return $resultCode;

    }

    /**
     * 支付
     * @param $code
     * @param float $amount
     * @return array|json数据，可直接填入js函数作为参数|成功时返回，其他抛异常
     */
	public function _getWxPay($code,$amount = 0.01){
		//$amount = 0.01;
		include APPPATH.'libraries/WxpayAPI/lib/WxPay.Api.php';
		include APPPATH.'libraries/WxpayAPI/example/WxPay.JsApiPay.php';
		
		$pay = new WxPayApi();
		$input = new WxPayUnifiedOrder();
		
		$input->SetBody('戈壁市集微信支付');
		$input->SetOut_trade_no($code);
		$input->SetTotal_fee($amount * 100);
		$input->SetTime_start(date("YmdHis"));
		$input->SetTime_expire(date("YmdHis", time() + 60 * 10));
		$input->SetNotify_url(getUrl('app/pay/wxCallback'));//回调
		$input->SetTrade_type('APP');
		$order = WxPayApi::unifiedOrder($input);
		
		if(empty($order)){
			return array('msg'=>'错误,订单数据为空');
		}elseif ($order['return_code'] == 'FAIL'){
			return $order;
		}elseif (! empty($order['err_code_des'])){
			return $order;
		}
		
		$parameters = array('msg'=>'生成预支付订单失败');
		if(! empty($order) && $order['return_code'] == 'SUCCESS' && $order['result_code'] == 'SUCCESS'){
			$tools = new JsApiPay();
			$parameters = $tools->GetAPPParameters($order);
		}
		
		return $parameters;
	}

    /**
     * 公众号支付
     * @param $code
     * @param float $amount
     * @return array|json数据，可直接填入js函数作为参数|成功时返回，其他抛异常
     */
	public function _getWeChatPay($code,$amount = 0.01){
//		$amount = 0.01;
		include APPPATH.'libraries/WxpayAPI2/lib/WxPay.Api.php';
		include APPPATH.'libraries/WxpayAPI2/example/WxPay.JsApiPay.php';

        //①、获取用户openid
//        $tools = new JsApiPay();
//        $openId = $tools->GetOpenid();
        $openId = wechat()->get_openid();
//p($openId);
        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody("戈壁市集微信支付");
        $input->SetAttach("戈壁市集微信支付");
        $input->SetOut_trade_no($code);
        $input->SetTotal_fee($amount*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("戈壁市集微信支付");
        $input->SetNotify_url(getUrl('pay/wxCallback'));
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = WxPayApi::unifiedOrder($input);


		if(empty($order)){
			return array('msg'=>'错误,订单数据为空');
		}elseif ($order['return_code'] == 'FAIL'){
			return $order;
		}elseif (! empty($order['err_code_des'])){
			return $order;
		}

		$parameters = array('msg'=>'生成预支付订单失败');
		if(! empty($order) && $order['return_code'] == 'SUCCESS' && $order['result_code'] == 'SUCCESS'){
			$tools = new JsApiPay();
            $parameters = $tools->GetJsApiParameters($order);
		}

		return $parameters;
	}

    /**
     * 微信退款
     * @param $code    预支付订单号
     * @param $totalAmount  订单总金额
     * @param $refundAmount   退款金额
     * @param $refundCode    退款单号即售后单号
     * @return array('return_code'=>'SUCCESS/FAIL', 'return_msg' => '返回信息，如非空，为错误原因')成功时返回
     */
    public function wxRefund($code, $totalAmount,$refundAmount, $refundCode){
        include APPPATH.'libraries/WxpayAPI/lib/WxPay.Api.php';

        $input = new WxPayRefund();
        $input->SetOut_trade_no($code);
        $input->SetTotal_fee($totalAmount*100);
        $input->SetRefund_fee($refundAmount*100);
        $input->SetOut_refund_no($refundCode);
        $input->SetOp_user_id(WxPayConfig::MCHID);
        $data = WxPayApi::refund($input);

        return $data;
    }

    /**
     * 微信公众号退款
     * @param $code    预支付订单号
     * @param $totalAmount  订单总金额
     * @param $refundAmount   退款金额
     * @param $refundCode    退款单号即售后单号
     * @return array('return_code'=>'SUCCESS/FAIL', 'return_msg' => '返回信息，如非空，为错误原因')成功时返回
     */
    public function WeChatRefund($code, $totalAmount,$refundAmount, $refundCode){
        include APPPATH.'libraries/WxpayAPI2/lib/WxPay.Api.php';

        $input = new WxPayRefund();
        $input->SetOut_trade_no($code);
        $input->SetTotal_fee($totalAmount*100);
        $input->SetRefund_fee($refundAmount*100);
        $input->SetOut_refund_no($refundCode);
        $input->SetOp_user_id(WxPayConfig::MCHID);
        $data = WxPayApi::refund($input);

        return $data;
    }

}